﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Glossary;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace StudentSolution
{
    public partial class StudentGUI : Form
    {
        private List<Word> takenExam;
        private string[] answers;
        private Languages currentExamLanguage;
        private int wordAt;
        private int cellOption;

        private BindingSource bindingSource = new BindingSource();
        private SqlDataAdapter dataAdapter = new SqlDataAdapter();

        public StudentGUI()
        {
            InitializeComponent();
            //this.Load += new System.EventHandler(StudentGUI_Load);
        }

        private void LoadExamsToGridView()
        {
            string studentId = personIdInput.Text.Trim();
            string sqlQuery = "SELECT ExamID, CourseID, DateCreated FROM ExamsForCoursesStudentIsEnrolledInView WHERE StudentID = '" + studentId + "'";
            GetExams(sqlQuery);
        }

        private void LoadCorrectedExamsToGridView()
        {
            // TODO!
            string sqlQuery = "";
        }

        public void GetExams(string sqlQuery)
        {
            FillGridWithQuestion(sqlQuery);
        }


        public void GetCorrectedExams(string sqlQuery)
        {
            FillGridWithQuestion(sqlQuery);
        }

        private void FillGridWithQuestion(string sqlQuery)
        {
            try
            {
                string connectionString = ConfigurationManager.ConnectionStrings["projectConnection"].ConnectionString;
                dataAdapter = new SqlDataAdapter(sqlQuery, connectionString);

                DataTable table = new DataTable();
                dataAdapter.Fill(table);

                bindingSource.DataSource = table;
                DbGridView.DataSource = bindingSource;
            }
            catch (SqlException)
            {
                MessageBox.Show("Error...");
            }
        }

        /// <summary>
        /// Input field for student Firstnamn.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FirstnameInput_TextChanged(object sender, EventArgs e)
        {
            if (firstnameInput != null) lastnameInput.Enabled = true;
        }

        /// <summary>
        /// Input field for student Lastname (street name and No.)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LastnameInput_TextChanged(object sender, EventArgs e)
        {
            if (lastnameInput != null) addressInput.Enabled = true;
        }

        /// <summary>
        /// Input field for student ADDRESS (street name and No.)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddressInput_TextChanged(object sender, EventArgs e)
        {
            if (addressInput != null) zipCodeInput.Enabled = true;
        }

        /// <summary>
        /// Input field for student ZIP CODE (5 digits)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>        
        private void ZipCodeInput_TextChanged(object sender, EventArgs e)
        {
            if (zipCodeInput != null) cityInput.Enabled = true;
        }

        /// <summary>
        /// Input field for student CITY
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CityInput_TextChanged(object sender, EventArgs e)
        {
            if (cityInput != null) personIdInput.Enabled = true;
        }

        private void personIdInput_TextChanged(object sender, EventArgs e)
        {
            if (personIdInput != null)
            {
                OpenExam.Enabled = true;
                GUICheckResults.Enabled = true;
            }
        }

        /// <summary>
        /// Initial button state: non-visible; turns visible once conditions are met (student info fields completed)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExamStart_Click(object sender, EventArgs e)
        {
            if (!CheckInformationBoxes())
            {
                statusLabel.Text = "Du måste fylla i alla dina uppgifter för att starta ett prov. YOLO!";
                return;
            }

            ExamBegin.Text = "Starta prov";
            ExamBegin.Enabled = true;
            StudentInfoBox.Enabled = false;
            LoadExamsToGridView();
        }

        /// <summary>
        /// STEP BACK to the previous word
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonPreviousWord_Click(object sender, EventArgs e)
        {
            answers[wordAt] = wordInput.Text; // maybe
            wordAt--;
            ShowNewWord();
            wordInput.Text = answers[wordAt];
            SetNextPreviousButtonState(wordAt, takenExam.Count - 1);
        }

        /// <summary>
        /// COMMITS the current WORD input to the program and COLLECTS the next word
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonNextWord_Click(object sender, EventArgs e)
        {
            answers[wordAt] = wordInput.Text;
            wordAt++;
            ShowNewWord();
            wordInput.Text = answers[wordAt];
            SetNextPreviousButtonState(wordAt, takenExam.Count - 1);
        }

        private void ShowNewWord()
        {
            wordOutput.Text = takenExam[wordAt].Foreign;
            counter.Text = String.Format("{0} / {1}", wordAt + 1, takenExam.Count);
        }

        private void SetNextPreviousButtonState(int positionInVector, int endNumber)
        {
            if (positionInVector <= 0)
            {
                previousWordButton.Enabled = false;
            }
            if (positionInVector >= 1)
            {
                previousWordButton.Enabled = true;
            }
            if (positionInVector <= endNumber - 1)
            {
                nextWordButton.Enabled = true;
                finishExamButton.Enabled = false;
            }
            if (positionInVector == endNumber)
            {
                nextWordButton.Enabled = false;
                finishExamButton.Enabled = true;
            }
            if (positionInVector >= endNumber)
            {
                previousWordButton.Enabled = true;
                nextWordButton.Enabled = false;
            }
        }

        /// <summary>
        /// COMMITS the entire test to the program ((auto-collects test results?))
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void FinishButton_Click(object sender, EventArgs e)
        {
            answers[wordAt] = wordInput.Text;
            for (int i = 0; i < takenExam.Count; i++)
            {
                takenExam[i].Answer = answers[i];
            }
            string[] personInformation = GetPersonInformation();

            SaveTakenExam();
            try
            {

                statusLabel.Text = "Provet är nu färdigt.";
            }
            catch (DirectoryNotFoundException)
            {
                statusLabel.Text = "Katalogen ditt provet sparas existerar ej.";
            }
            catch
            {
                statusLabel.Text = "Ett fel uppstod.";
            }
            ResetProgram();
        }

        private void SaveTakenExam()
        {
            using (var con = new SqlConnection())
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["projectConnection"].ConnectionString;
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                wordOutput.Text = DateTime.Now.ToString("yyyy/MM/dd");
                System.Threading.Thread.Sleep(5000);
                StringBuilder sb = new StringBuilder();
                sb.Append(
                    string.Format("INSERT INTO UncorrectedExams (ExamID, StudentID, TakenDate) VALUES ({0}, '{1}', '{2}') "
                        , cellOption, personIdInput.Text, DateTime.Now.ToString("yyyy/MM/dd")));
                sb.Append(" INSERT INTO Answers (UncorrectedExamID, WordID, Answer) VALUES ");
                for (int i = 0; i < takenExam.Count - 1; i++)
                {
                    sb.Append(string.Format("((IDENT_CURRENT('UncorrectedExams')), {0}, '{1}'), ", takenExam[i].WordID, answers[i]));
                }
                sb.Append(string.Format("((IDENT_CURRENT('UncorrectedExams')), {0}, '{1}')", takenExam[takenExam.Count - 1].WordID, answers[takenExam.Count - 1]));

                cmd.CommandText = sb.ToString();
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }


        /// <summary>
        /// Resets the form.
        /// </summary>
        private void ResetProgram()
        {
            wordInput.Text = "";
            wordOutput.Text = "";

            firstnameInput.Text = "";
            lastnameInput.Text = "";
            addressInput.Text = "";
            zipCodeInput.Text = "";
            cityInput.Text = "";
            personIdInput.Text = "";

            firstnameInput.Enabled = true;
            lastnameInput.Enabled = false;
            addressInput.Enabled = false;
            zipCodeInput.Enabled = false;
            cityInput.Enabled = false;
            personIdInput.Enabled = false;
            previousWordButton.Enabled = false;
            finishExamButton.Enabled = false;

            ExamBox.Enabled = false;
            StudentInfoBox.Enabled = true;


            OpenExam.Enabled = false;

        }

        private string[] GetPersonInformation()
        {
            string[] returnString = new string[5];
            returnString[0] = firstnameInput.Text;
            returnString[1] = lastnameInput.Text;
            returnString[2] = addressInput.Text;
            returnString[3] = zipCodeInput.Text;
            returnString[4] = cityInput.Text;
            return returnString;
        }

        /// <summary>
        /// Disabled by default
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckResults_Click(object sender, EventArgs e)
        {
            //string[] information = new string[5];
            //OpenFileDialog fileDialog = new OpenFileDialog();

            //fileDialog.InitialDirectory = Directory.GetCurrentDirectory() + "\\CorrectedExams\\";
            //if (!Directory.Exists(fileDialog.InitialDirectory))
            //{
            //    statusLabel.Text = "Prov katalogen existerar ej.";
            //    return;
            //}

            //fileDialog.ShowDialog();
            //if (!File.Exists(fileDialog.FileName))
            //{
            //    statusLabel.Text = "Provet existerar inte.";
            //    return;
            //}
            //List<Word> exam = Output.ReadCorrectedExam(fileDialog.FileName, ref information);
            //Glossblad gb = new Glossblad(exam, information);
            //gb.Show();
            LoadCorrectedExamsToGridView();
            ExamBegin.Text = "Visa prov";
        }

        private bool CheckInformationBoxes()
        {
            if (firstnameInput.Text == "" || lastnameInput.Text == "" || addressInput.Text == "" || zipCodeInput.Text == "" || cityInput.Text == "")
            {
                return false;
            }
            else
                return true;
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void ExamBegin_Click(object sender, EventArgs e)
        {
            takenExam = new List<Word>();
            DbGridView.DataSource = null;
            ExamBox.Enabled = true;

            string sqlQuery = string.Format("SELECT WordID, ForeignWord, SwedishWord FROM ShowAnExamView WHERE ExamID = {0}", cellOption);
            try
            {

                string connectionString = ConfigurationManager.ConnectionStrings["projectConnection"].ConnectionString;
                dataAdapter = new SqlDataAdapter(sqlQuery, connectionString);

                DataTable table = new DataTable();
                dataAdapter.Fill(table);

                Word tempWord;
                foreach (DataRow dataRow in table.Rows)
                {
                    tempWord = new Word(
                        dataRow.ItemArray[1].ToString(),
                        dataRow.ItemArray[2].ToString(),
                        dataRow.ItemArray[0].ToString());
                    takenExam.Add(tempWord);
                }
                answers = new string[takenExam.Count];
                wordOutput.Text = takenExam[0].Foreign;

            }
            catch (SqlException)
            {
                MessageBox.Show("Error...");
            }
        }

        private void DbGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            cellOption = (int)DbGridView.Rows[e.RowIndex].Cells[0].Value;
            statusLabel.Text = cellOption.ToString();
            ExamBegin.Enabled = true;
        }


    }
}
